package br.ufal.tci.nexos.arcolive.service.connection.command;

import br.ufal.tci.nexos.arcolive.ArCoLIVEServiceManager;
import br.ufal.tci.nexos.arcolive.command.ArCoLIVEClientCommand;
import br.ufal.tci.nexos.arcolive.command.ArCoLIVECommandResult;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotRemoveParticipantException;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.service.connection.ConnectionRequest;

public class DisconnectConnectionCommand extends ArCoLIVEClientCommand {
	
	public DisconnectConnectionCommand(ConnectionRequest request) {
		super(request);
	}
	
	public ArCoLIVECommandResult executeImpl() {
		ArCoLIVEParticipant participant = (ArCoLIVEParticipant)this.request.getOwner();
		int protocolId = this.request.getProtocolId();
		String requestId = this.request.getStringParameter("requestId");
		ArCoLIVEServiceManager serviceManager = ArCoLIVEServiceManager.getInstance();
		String response = protocolId + "#requestId=" + requestId + "#response=";
		
		try {
			serviceManager.removeParticipantFromAllService(participant);
			response += "1";
			participant.getConnectionService().getConnection().sendMessage(response);
			participant.getConnectionService().stopService();
			participant = null;
			System.gc();
		} catch (ArCoLIVECannotRemoveParticipantException e) {
			response += "0";
			participant.getConnectionService().getConnection().sendMessage(response);
			return new ArCoLIVECommandResult(this, response, e);
		}
		
		return new ArCoLIVECommandResult(this, response);
		
	}

}